import React from "react";
import { useLocation } from "react-router-dom";
import { createForm } from "@formily/core";
import { createSchemaField } from "@formily/react";
import api from "src/http/api";
import useSchema from "./schema";
import { getParams } from "src/utils/index";
import {
  Form,
  FormItem,
  FormCollapse,
  Space,
  Input,
  Select,
  Radio,
  ArrayCards,
  ArrayItems,
  Submit,
} from "@formily/antd";
import { Typography, Row, Col, Select as AntdSelect, notification } from "antd";
import Div from "src/components/Div";
import FetchSelect from "src/components/FetchSelect";
import OwnersSelect from "src/components/OwnersSelect";
import OpenInnerFieldsModalButton from "src/components/OpenInnerFieldsModalButton";
import {
  EntityFormProps,
  EntityMongodbFormDataProps,
  Field,
  EntityProps,
  MappingProps,
} from "src/utils/interface";

import styles from "./index.scss";

const { useState, useEffect } = React;

interface Props {
  storageUri: string;
  idc: string[];
  initValues: EntityFormProps;
}

const EntityMysqlForm: React.FC<Props> = (props) => {
  const { operate, entityName } = getParams(useLocation().search);

  const [initialValues, setInitialValues] = useState({
    fields: [{}],
    indexs: [{ primary: true }],
  } as EntityMongodbFormDataProps);

  const form = createForm({
    initialValues,
  });

  // @ts-ignore
  const formCollapse = FormCollapse.createFormCollapse();

  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Div,
      FormCollapse,
      Space,
      Input,
      Select,
      FetchSelect,
      Radio,
      AntdSelect,
      OwnersSelect,
      OpenInnerFieldsModalButton,
      ArrayCards,
      ArrayItems,
    },
  });

  const addSchema = useSchema({
    formCollapse,
    storageUri: props.storageUri,
    idc: props.idc,
    schemaType: "add",
  });

  const editSchema = useSchema({
    formCollapse,
    storageUri: props.storageUri,
    entityName,
    idc: props.idc,
    schemaType: "edit",
  });

  const getInitValues = (data: EntityFormProps): EntityMongodbFormDataProps => {
    const entityName = data.entity.entityName.split("-").slice(1).join("-");
    const baseInfo = {
      entityName,
      description: data.entity.description,
      owners: data.entity.owners,
      storageUri: data.mapping.storageUri,
      tableName: data.mapping.tableName,
      idcs: data.mapping.idcs,
    };
    const fields = data.entity.fields;
    const indexs = data.entity.indexs;
    const formData: EntityMongodbFormDataProps = {
      baseInfo,
      fields,
      indexs,
    };
    return formData;
  };

  const handleClick = async () => {
    const err = await form.validate();
    if (err) return;

    const { baseInfo, fields, indexs } = form.values;

    const prefix = props.storageUri?.split("-")[0];
    const entityName = `${prefix}-${baseInfo.entityName}`;

    const entity = {
      entityName,
      description: baseInfo.description,
      owners: baseInfo.owners,
      fields,
      indexs,
    } as EntityProps;

    const mapping = {
      entityName,
      storageUri: baseInfo.storageUri,
      tableName: baseInfo.tableName,
      idcs: baseInfo.idcs,
    } as MappingProps;

    const formData: EntityFormProps = {
      entity: { ...entity, entityName },
      mapping,
    };

    if (operate === "add") {
      return api.addEntity(formData).then((res) => {
        notification.success({
          message: "Success",
          description: "创建 Entity、Mapping 成功",
          top: 65,
        });
      });
    }

    api.editEntity(formData, entityName).then((res) => {
      notification.success({
        message: "Success",
        description: "编辑 Entity、Mapping 成功",
        top: 65,
      });
    });
  };

  useEffect(() => {
    if (operate !== "edit") return;
    if (props.initValues.entity) {
      setInitialValues(getInitValues(props.initValues));
    }
  }, [props.initValues, operate]);

  return (
    <div className={(styles as any).content}>
      <Typography.Title level={3} style={{ textAlign: "center" }}>
        {`${operate === "add" ? "创建" : "编辑"} Entity & Mapping`}
      </Typography.Title>

      <Form form={form} labelCol={6} wrapperCol={16} onAutoSubmit={console.log}>
        <Row>
          <Col span={2} offset={6}>
            <Typography.Title level={4}>Entity</Typography.Title>
          </Col>
          <Col span={2} offset={10}>
            <Typography.Title level={4}>Mapping</Typography.Title>
          </Col>
        </Row>
        <SchemaField schema={operate === "add" ? addSchema : editSchema} />
        <Submit
          block
          size="large"
          style={{ marginTop: 22 }}
          onClick={handleClick}
        >
          提交
        </Submit>
      </Form>
    </div>
  );
};

export default EntityMysqlForm;
